import json
import re

from django.contrib.auth import login
from django.http import JsonResponse
# Create your views here.
from django.views import View
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.user.models import User, Address


# 登录
from apps.user.serializers.user import UserAddressSerializer


class RegisterView(View):
    def post(self, request):
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        sms_code = json_dict.get('sms_code')

        if not all([username, password, password2, mobile, sms_code]):
            return JsonResponse({"code": "400", "errmsg": "缺少参数"})
        # 判断用户名是否是5-20个字符
        # if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
        #     return JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})
        # # 判断密码是否是8-20个数字
        # if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
        #     return JsonResponse({'code': 400, 'errmsg': 'password格式有误!'})
        # # 判断两次密码是否一致
        # if password != password2:
        #     return JsonResponse({'code': 400, 'errmsg': '两次输入不对!'})
        # # 判断手机号是否合法
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})
        # 判断是否勾选用户协议
        # if allow != True:
        #     return JsonResponse({'code': 400, 'errmsg': 'allow格式有误!'})
        # return JsonResponse({"code": 0, "errmsg": "ok"})

        try:
            print(username, password, mobile)
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
            # 密码加密   数据保存可能不成功捕获异常
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': "用户保存失败"})

        login(request, user)

        return JsonResponse({'code': 0, 'errmsg': '注册成功!'})


# 修改密码
class RepasswordView(APIView):

    def post(self, request):
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        old_password = json_dict.get('old_password')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        username = json_dict.get('username')

        print(111111, request.user)
        # 2.检查密码是否正确

        result = request.user.check_password(old_password)
        if not all([old_password, password, password2]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全!'})

        if not result:
            return JsonResponse({'code': 400, 'errmsg': '原始密码不正确'})

        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次密码不一样!'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '密码最少8位,最长20位'})

        # 3.从数据库修改密码
        try:
            request.user.set_password(password)
            request.user.save()
            print("修改成功")
            return JsonResponse({'code': 0, 'errmsg': '修改密码成功'})
        except Exception as e:
            print("修改密码失败", e)
            return JsonResponse({'code': 400, 'errmsg': '修改密码失败'})


# 查询用户信息
class UserInfoView(APIView):
    def get(self, request):
        info_data = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active,
            'last_login': request.user.last_login
        }

        return JsonResponse({
            'code': 0,
            'errmsg': '个人中心',
            "info_data": info_data
        })


# 修改用户信息

class UpdateUserView(APIView):

    def post(self,request):
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        username = json_dict.get('username')
        mobile = json_dict.get('mobile')
        email = json_dict.get('email')

        if not all([username, mobile, email]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全!'})

        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})

        if not re.match(r'^[a-z0-9][\w\\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({"code": "400", "errmsg": "邮箱地址格式错误"})
        # print(request.user.id)
        try:
            User.objects.filter(id = request.user.id).update(
                username=username,
                mobile=mobile,
                email=email
            )

            # 密码加密   数据保存可能不成功捕获异常
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': "用户保存失败"})

        return JsonResponse({"code": "0", "errmsg": "修改成功"})



# 添加地址、
class AddressCreateView(APIView):
    def post(self, request):
        # 1.获取数据
        body = request.body

        data_dict = json.loads(body)

        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")
        # 2.是否为空
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})

        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        user = request.user
        try:
            address = Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
            print("数据保存成功")
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '保存数据失败'})


        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, "errmsg": "ok", "address": address_dict})



class AddressView(APIView):
    def get(self, request):
        user = request.user
        addresses = Address.objects.filter(user_id=request.user.id, is_deleted=False)

        addresses_list = []

        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok', "addresses": addresses_list})




class AddressRemoveView(APIView):
    def delete(self, request, address_id):
        # 逻辑删除 把is_deleted改为True
        try:
            address = Address.objects.get(id=address_id)

            address.is_deleted = True
            address.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '删除数据失败'})

        return JsonResponse({'code': 0, 'errmsg': '删除成功'})

    def put(self, request, address_id):
        body = request.body

        data_dict = json.loads(body)
        # 1.获取数据
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})

        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return JsonResponse({'code': 400, 'errmsg': '参数email有误'})
        user = request.user
        # 2.查询数据库
        try:
            Address.objects.filter(id=address_id).update(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
            print("数据修改成功")
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '数据修改失败'})
        # 3.返回一个字典
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, "errmsg": "ok", "address": address_dict})